﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinServiceKeepAliveTest
{
    public partial class Form1 : Form
    {
        LogHelper log = new LogHelper();

        public Form1()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 在文件夹里以管理员身份运行哦，编辑器里没权限
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            ExecIntervalMinuteFunc();
        }

        /// <summary>
        /// ExecIntervalMinuteFunc
        /// </summary>
        private void ExecIntervalMinuteFunc()
        {
            string serviceName = ConfigurationManager.AppSettings["ServiceName"].ToString();
            if (string.IsNullOrEmpty(serviceName))
            {
                log.WriteLog("配置文件中没有指定服务名称！");
                ShowMessage("配置文件中没有指定服务名称！");
                return;
            }
            string[] serviceArray = serviceName.Split(',');
            List<string> serviceNameList = new List<string>(serviceArray);
            foreach (string serviceNameItem in serviceNameList)
            {
                try
                {
                    if (ServiceHelper.ISWindowsServiceInstalled(serviceNameItem))
                    {
                        if (!ServiceHelper.ISStart(serviceNameItem))
                        {
                            bool runStatus = ServiceHelper.StartService(serviceNameItem);
                            if (runStatus)
                            {
                                log.WriteLog($"服务 {serviceNameItem} 启动成功！");
                                ShowMessage($"服务 {serviceNameItem} 启动成功！");
                            }
                            else
                            {
                                log.WriteLog($"服务 {serviceNameItem} 启动失败！");
                                ShowMessage($"服务 {serviceNameItem} 启动失败！");
                            }
                        }
                    }
                    else
                    {
                        log.WriteLog($"服务 {serviceNameItem} 未安装！");
                        ShowMessage($"服务 {serviceNameItem} 未安装！");
                    }
                }
                catch (Exception ex)
                {
                    log.WriteExceptionLog(ex);
                    ShowMessage("执行异常！");
                }
            }
        }

        private void ShowMessage(string message)
        {
            if (!string.IsNullOrEmpty(message))
            {
                richTextBox1.Text += message + "\r\n";
            }
        }
    }
}
